<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app'
import { switchNavBarTheme } from '@/utils/common'
import { reactive, ref } from 'vue'
import type { FormRules } from 'wot-design-uni/components/wd-form/types'
import type { UploadMethod, UploadFile } from 'wot-design-uni/components/wd-upload/types'
import { useToast } from 'wot-design-uni'
import { AuthStatus } from '@/types/constants'
import { createOrUpdateDriverAuthInfoAPI, driverLicenseOcrAPI, idCardOcrAPI } from '@/api/user'
import type { AuthInfoDTO, DriverLicenseOcrVO, IdCardOcrVO } from '@/types/user'

const toast = useToast()
onLoad((option) => {
  switchNavBarTheme()
  if (option) {
    toast.show({
      msg:
        option.authStatus == AuthStatus.NO_AUTH ? '当前未认证，请认证' : '认证已过期，请重新认证',
      position: 'top',
    })
  }
})

const form = ref()
const idCard = reactive<IdCardOcrVO>({
  name: '',
  sex: null,
  birthDate: '',
  idNumber: '',
  address: '',
  idCardExpireDate: '',
  idCardFrontUrl: '',
  idCardBackUrl: '',
})
const driverLicense = reactive<DriverLicenseOcrVO>({
  name: '',
  idNumber: '',
  driverLicenseClass: '',
  driverLicenseIssueDate: '',
  driverLicenseExpireDate: '',
  driverLicenseUrl: '',
})
const model = reactive<AuthInfoDTO>({
  name: '',
  sex: null,
  birthDate: '',
  idNumber: '',
  address: '',
  idCardExpireDate: '',
  idCardFrontUrl: '',
  idCardBackUrl: '',
  driverLicenseClass: '',
  driverLicenseIssueDate: '',
  driverLicenseExpireDate: '',
  driverLicenseUrl: '',
  carBrand: '',
  carColor: '',
  plateNumber: '',
})
const rules: FormRules = {
  idCardFrontUrl: [{ required: true, message: '请上传身份证正面' }],
  idCardBackUrl: [{ required: true, message: '请上传身份证反面' }],
  driverLicenseUrl: [{ required: true, message: '请上传驾驶证' }],
  carBrand: [{ required: true, message: '请输入车品牌' }],
  carColor: [{ required: true, message: '请输入车颜色' }],
  plateNumber: [{ required: true, message: '请输入车牌号' }],
}
const idCardFrontUrl = ref<UploadFile[]>([])
const idCardBackUrl = ref<UploadFile[]>([])
const driverLicenseUrl = ref<UploadFile[]>([])

const idCardFrontUpload: UploadMethod = async (file, formData, options) => {
  const res = await idCardOcrAPI(file.url)
  if (res.code == 200 && res.data.name !== null) {
    Object.assign(idCard, res.data)
    model.idCardFrontUrl = idCard.idCardFrontUrl
    idCardFrontUrl.value = [{ url: idCard.idCardFrontUrl }]
  } else {
    toast.show('上传失败，请重写上传身份证正面图片')
    idCardFrontUrl.value = []
  }
}
const idCardBackUpload: UploadMethod = async (file, formData, options) => {
  const res = await idCardOcrAPI(file.url)
  if (res.code == 200 && res.data.name === null) {
    idCard.idCardExpireDate = res.data.idCardExpireDate
    idCard.idCardBackUrl = res.data.idCardBackUrl
    model.idCardBackUrl = idCard.idCardBackUrl
    idCardBackUrl.value = [{ url: idCard.idCardBackUrl }]
  } else {
    toast.show('上传失败，请重写上传身份证反面图片')
    idCardBackUrl.value = []
  }
}
const driverLicenseUpload: UploadMethod = async (file, formData, options) => {
  const res = await driverLicenseOcrAPI(file.url)
  if (res.code == 200 && res.data.name !== null) {
    Object.assign(driverLicense, res.data)
    model.driverLicenseUrl = driverLicense.driverLicenseUrl
    driverLicenseUrl.value = [{ url: driverLicense.driverLicenseUrl }]
  } else {
    toast.show('上传失败，请重写上传驾驶证图片')
    driverLicenseUrl.value = []
  }
}
const submit = () => {
  form.value.validate().then(async ({ valid }: { valid: boolean }) => {
    if (valid) {
      if (idCard.idNumber !== driverLicense.idNumber) return toast.show('身份证和驾驶证不匹配，请重新上传')
      if (new Date(idCard.idCardExpireDate) < new Date(Date.now()) || new Date(driverLicense.driverLicenseExpireDate) < new Date(Date.now())) {
        return toast.show('驾驶证或身份证已过期，请重新上传')
      }
      if (model.carBrand.trim() === '') return toast.show('汽车品牌不能为空')
      if (model.carColor.trim() === '') return toast.show('汽车颜色不能为空')
      if (model.plateNumber.trim() === '') return toast.show('车牌号不能为空')
      // 校验车牌
      if (!/^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z][A-Z][A-Z0-9]{4}[A-Z0-9挂学警港澳]$/.test(model.plateNumber)) {
        return toast.show('车牌号格式不正确，请重新输入')
      }
      Object.assign(model, idCard, driverLicense)
      const res = await createOrUpdateDriverAuthInfoAPI(model)
      if (res.code === 200) {
        setTimeout(() => {
          uni.showToast({ title: '认证成功', icon: "none" });
        }, 100)
        uni.navigateBack()
      }
      else toast.show(res.msg)
    }
  })
}
</script>

<template>
  <wd-toast />
  <view class="back">
    <view class="content">
      <wd-form ref="form" :model="model" :rules="rules">
        <wd-cell-group border>
          <wd-cell title="身份证正面" title-width="100px" prop="idCardFrontUrl">
            <wd-upload
              :file-list="idCardFrontUrl"
              :limit="1"
              :show-limit-num="false"
              :upload-method="idCardFrontUpload"
            />
          </wd-cell>
          <wd-cell title="身份证反面" title-width="100px" prop="idCardBackUrl">
            <wd-upload
              :file-list="idCardBackUrl"
              :limit="1"
              :show-limit-num="false"
              :upload-method="idCardBackUpload"
            />
          </wd-cell>
          <wd-cell title="驾驶证" title-width="100px" prop="driverLicenseUrl">
            <wd-upload
              :file-list="driverLicenseUrl"
              :limit="1"
              :show-limit-num="false"
              :upload-method="driverLicenseUpload"
            />
          </wd-cell>
          <wd-input
            v-model="model.carBrand"
            label="汽车品牌"
            label-width="100px"
            prop="carBrand"
            placeholder="请输入车品牌"
            clearable
          />
          <wd-input
            v-model="model.carColor"
            label="汽车颜色"
            label-width="100px"
            prop="carColor"
            placeholder="请输入车颜色"
            clearable
          />
          <wd-input
            v-model="model.plateNumber"
            label="车牌号"
            label-width="100px"
            prop="plateNumber"
            placeholder="请输入车牌号"
            clearable
          />
        </wd-cell-group>
      </wd-form>
      <view class="button">
        <wd-button @click="submit">提交</wd-button>
      </view>
    </view>
  </view>
</template>

<style scoped lang="scss">
.back {
  background-color: var(--back-color);
  display: flex;
  justify-content: center;
  padding: 30rpx 0;
  .content {
    width: 90%;
    background-color: var(--front-color);
    padding: 50rpx 2%;
    .button {
      display: flex;
      margin-top: 30rpx;
    }
  }
}
</style>
